const Router = require('koa-router')
const requireDirectory = require('require-directory')
const koaBody = require('koa-body');
const ExcepitonMiddleware = require('../middleware/exception')

class Manager {
  constructor (app) {
    this.app = app
    // 设置cookie 签名密钥
    this.app.keys = ['xinlang']
  }

  initBodyParser () {
    this.app.use(koaBody({multipart:true, parsedMethods: ['POST', 'PUT', 'PATCH', 'GET', 'HEAD', 'DELETE']}))
    return this
  }

  initException () {
    this.app.use(ExcepitonMiddleware)
    return this
  }

  initRouter (routeDir) {
    requireDirectory(module, routeDir, {
      visit: (routeModule) => {
        if (routeModule instanceof Router) {
          this.app.use(routeModule.routes())
          this.app.use(routeModule.allowedMethods())
        }
      }
    })
  }
}
module.exports = Manager
